import Vue from 'vue'
import Vuex from 'vuex'
import { getCartTotal, getCartList, UpdateCartService, DeleteCartService } from '@/api/cart'

Vue.use(Vuex)

export default {
  namespaced: true,
  state () {
    return {
      total: 0,
      cartList: []
    }
  },
  mutations: {
    async getCartTotal (state) {
      const { data: { cartTotal } } = await getCartTotal()
      state.total = cartTotal
    },
    async getCartListData (state) {
      const { data } = await getCartList()
      data.list.forEach(item => {
        item.isChecked = true
      })
      state.cartList = data.list
    },
    toggleCheck (state, id) {
      const obj = state.cartList.find(item => item.goods_id === id)
      obj.isChecked = !obj.isChecked
    },
    toggleAllCheck (state, flag) {
      state.cartList.forEach(item => {
        item.isChecked = flag
      })
    },
    setGoodsCount (state, obj) {
      const o = state.cartList.find(item => item.goods_id === obj.goodsId)
      o.goods_num = obj.goodsNum
    }
  },
  actions: {
    InitCartTotal (context) {
      context.commit('getCartTotal')
    },
    InitCartList (context) {
      context.commit('getCartListData')
    },
    async UpdateCartGoodsNum (context, obj) {
      context.commit('setGoodsCount', obj)
      await UpdateCartService(obj)
    },
    async DeleteCart (context, cartIds) {
      await DeleteCartService({ cartIds })
      context.commit('getCartListData')
      context.commit('getCartTotal')
    }
  },
  getters: {
    isAll (state) {
      return state.cartList.every(item => item.isChecked)
    },
    totalPrice (state) {
      return state.cartList.reduce((sum, item) => sum + (item.isChecked ? item.goods_num * item.goods.goods_price_min : 0), 0).toFixed(2)
    },
    totalNum (state) {
      return state.cartList.filter(item => item.isChecked).length
    },
    cartIds (state) {
      return state.cartList.filter(item => item.isChecked).map(item => item.id).join()
    }
  }
}
